package com.qzl.common.netty.config;

import cn.hutool.core.lang.UUID;
import com.qzl.common.common.RespConstant;
import com.qzl.common.netty.model.UserModel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;


/**
 * @author: qzl
 * @date : 2025/6/24 9:00
 * @description:
 */
@Slf4j
public class UserConfig {
    // 用户，密码
    public static Map<String, String> userPassMap = new HashMap<>();
    // token，用户
    public static Map<String, UserModel> tokenUserMap = new HashMap<>();
    // token，用户
    public static Map<String, String> userTokenMap = new HashMap<>();
    // 用户，通道
    public static Map<String, ChannelHandlerContext> userChannelMap = new HashMap<>();
    public static Map<ChannelHandlerContext, String> channelUserMap = new HashMap<>();

    public static String getUserPass(String name) {
        return userPassMap.get(name);
    }

    static {
        userPassMap.put("zs", "123");
        userPassMap.put("ls", "123");
        userPassMap.put("ww", "123");
    }

    public static String login(UserModel user, ChannelHandlerContext ctx) {
        String pass = userPassMap.get(user.getUsername());
        if (StringUtils.isBlank(pass)) {
            return  RespConstant.USERNAME_PASSWORD_ERROR.getMessage();
        }
        if (!pass.equals(user.getPassword())) {
            return  RespConstant.USERNAME_PASSWORD_ERROR.getMessage();
        }
        String uuid = UUID.randomUUID().toString();
        tokenUserMap.put(uuid, user);
        userTokenMap.put(user.getUsername(), uuid);
        userChannelMap.put(user.getUsername(), ctx);
        channelUserMap.put(ctx, user.getUsername());
        log.info("在线用户：{}", StringUtils.join(userChannelMap.keySet(),","));
        return uuid;
    }

    public static void logOut(String token){
        String username = tokenUserMap.get(token).getUsername();
        tokenUserMap.remove(token);
        userTokenMap.remove(username);
        ChannelHandlerContext channel = userChannelMap.get(username);
        userChannelMap.remove(username);
        channelUserMap.remove(channel);
    }
    public static void logOut(ChannelHandlerContext channel){
        String username = channelUserMap.get(channel);
        userChannelMap.remove(username);
        channelUserMap.remove(channel);
        String token = userTokenMap.get(username);
        tokenUserMap.remove(token);
        userTokenMap.remove(username);
    }
}
